// components/IndexBar.js
const APP = getApp();
/**
 * 上线前：请隐藏日志输入代码
 */
Component({

    lifetimes: {
        attached: function() {
            // 在组件实例进入页面节点树时执行

            //【在data中设置回调方法】
            let _this = this;
            //设置数据源(数据结构{A:[],B:[cityId:201,cityName:'北京'],...Z:[]})
            this.data.setData = function(datasource){
                //组装搜索数据源
                let tmpList = [];
                for (let item in datasource) {
                    tmpList = tmpList.concat(datasource[item]);
                }
                //临时键数组
                let tmpKeys = Object.keys(datasource);
                _this.setData({
                    unitKeys: datasource,
                    unitList: tmpList,
                    letters: tmpKeys,
                    keySelector: tmpKeys[0],
                }, function () {
                    _this.initSidebar();
                    _this.initCityElement();
                    APP.applog.info(['数据源1', _this.data.unitList]);
                    APP.applog.info(['数据源2', _this.data.letters]);
                });
            };
            //绑定事件： bindIndexbarSynchReffer
            this.triggerEvent('IndexbarSynchReffer',this); //【注意】事件名称区分大小写
        },
        ready:function(){
            // 在组件在视图层布局完成后执行
            this.init();
        },
        detached: function() {
          // 在组件实例被从页面节点树移除时执行
        },
    },

    /**
     * 组件的属性列表
     */
    properties: {

    },

    /**
     * 组件的初始数据
     */
    data: {
        scrollviewHeight: 0,
        keySelector: '',
        unitKeys: {},
        unitKeyPosition: [], //健位置
        unitList: [],
        letters: [
            // 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
        ],
        sidebar: null,
        isSidebarActived: false,
        //查询
        keyword: '',
        searchCityList: [],
    },

    /**
     * 组件的方法列表
     */
    methods: {

        init(callback) {
            this.initCityView();
            callback && callback();
        },

        initCityView() {
            let _this = this;
            //  高度自适应
            APP.apptool.setAutoSize(function (res, sysRes) {
                // res结构{cwidth, cheight, rpxRate, pixelRatio}
                _this.setData({
                    scrollviewHeight: res.cheight - 100
                });
            });
        },

        initCityElement() {
            //数据加载完毕后才可以调用此处代码
            let _this = this;
            let query = wx.createSelectorQuery().in(this);
            query.selectAll('.sitem .title').boundingClientRect(function (res) {
                APP.applog.info(['Scroll-View内部元素属性值', res]);
                //数据元素格式{bottom，dataset，height，id，left，right，top，width}
                _this.data.unitKeyPosition = Array.from(res); // [...res];
            }).exec();
        },

        initSidebar() {
            //数据加载完毕后才可以调用此处代码
            let _this = this;
            let query = wx.createSelectorQuery().in(this);
            query.select('.bar').boundingClientRect().exec(function (res) {
                APP.applog.info(['字母索引数据（原始）', res]);
                let tmpSidebar = res[0];
                tmpSidebar.rpix = tmpSidebar.width / 40; //像素比
                tmpSidebar.padding = tmpSidebar.rpix * 20; //索引栏填充
                tmpSidebar.letterHeight = (tmpSidebar.height - 2 * tmpSidebar.padding) / _this.data.letters.length; //索引元素高(默认26)
                tmpSidebar.letterRangeY = [tmpSidebar.top + tmpSidebar.padding, tmpSidebar.top + tmpSidebar.height - tmpSidebar.padding]; //索引Y偏移区间
                _this.data.sidebar = tmpSidebar; //索引栏数据对象
                APP.applog.info(['字母索引数据（最新）', res]);
            });
        },

        //滑动单位显示字母
        doScrollLetter(scroll) {
            if (!scroll) return;
            if (this.data.unitKeyPosition.length < 1) return;

            //查找接近字母项
            APP.applog.debug(this.data.unitKeyPosition, '字母列表位置信息');
            let tmpScrollTopPadding = this.data.sidebar.rpix * 60;
            let tmpLastIndex = 0;
            for (let i = 0; i < this.data.unitKeyPosition.length; i++) {
                APP.applog.debug([this.data.unitKeyPosition[i].top, scroll.scrollTop + tmpScrollTopPadding + this.data.unitKeyPosition[i].height], '字母距顶，滚动距顶');
                if (this.data.unitKeyPosition[i].top > scroll.scrollTop + tmpScrollTopPadding + this.data.unitKeyPosition[i].height) {
                    tmpLastIndex = i;
                    break;
                }
            }
            if (tmpLastIndex < 1) return; //低于1终止运行
            let tmpLetter = this.data.unitKeyPosition[tmpLastIndex - 1];
            APP.applog.debug(tmpLetter, 'tmpLetter');
            if (this.data.keySelector == tmpLetter) return; //重复，终止运行
            this.setData({
                keySelector: tmpLetter.id,
            });
        },

        //选择单位
        doCitySelector(e) {
            let dataset = e.currentTarget.dataset;
            let backResult = {
                cityId: dataset.id,
                cityName: dataset.name,
            };
            APP.apptool.navigateBackPage(1, function (targetPage) {
                //需刷新数据面，必须实现 doSetResult() 方法
                targetPage.doSetResult(backResult);
            });
        },

        //定位索引
        doLocalLetter(touchEvent) {
            if (!this.data.sidebar) return;

            APP.applog.info(['触屏事件', touchEvent]);

            let tmpTouchEvent = touchEvent.touches[0]
            let letterIndex = Math.ceil((tmpTouchEvent.pageY - this.data.sidebar.letterRangeY[0]) / this.data.sidebar.letterHeight);
            if (letterIndex > this.data.letters.length) return; //索引过界，终止运行
            let letter = this.data.letters[letterIndex - 1];
            if (this.data.keySelector == letter) return; //重复，终止运行

            this.setData({
                keySelector: this.data.letters[letterIndex - 1],
            });
        },

        //查询
        bindInputConfirm(e) {
            let value = e.detail.value;
            if (this.data.unitList.length < 1) return;

            this.setData({
                searchCityList: this.data.unitList.filter((item) => {
                    return item.cityName.indexOf(value) != -1;
                }),
                keyword: value,
            });
        },
        //取消查询
        bindClear(e) {
            this.setData({
                keyword: '',
                searchCityList: []
            });
        },

        //触屏开始
        bindLetterStart(e) {
            // APP.applog.info(['触屏开始',e]);
            this.setData({
                isSidebarActived: true
            });
            this.doLocalLetter(e);
        },
        //触屏滑动
        bindLetterMove(e) {
            // APP.applog.info(['触屏滑动',e]);
            this.doLocalLetter(e);
        },
        //触屏结束
        bindLetterEnd(e) {
            // APP.applog.info(['触屏结束',e]);
            this.setData({
                isSidebarActived: false
            });
        },
        //触屏终断
        bindLetterCancel(e) {
            // APP.applog.info(['触屏终断',e]);
            this.setData({
                isSidebarActived: false
            });
        },
        //单位滚动
        bindCityScroll(e) {
            // {scrollLeft, scrollTop, scrollHeight, scrollWidth, deltaX, deltaY}
            APP.applog.info(['滚动事件', e]);
            let detail = e.detail;
            this.doScrollLetter(detail);
        },
    }
})